<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单管理
 *
 * @icon fa fa-shopping-cart
 */
class Order extends Backend
{
    /**
     * Order模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 优化后的查询：先获取订单基础数据，避免使用MAX函数
            $total = Db::name('order')->where($where)->count();
            
            // 第一步：获取订单基础数据
            $orderList = Db::name('order')
                ->field('o.*')
                ->alias('o')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            
            if (empty($orderList)) {
                $result = array("total" => $total, "rows" => []);
                return json($result);
            }
            
            // 提取订单ID列表
            $orderIds = array_column($orderList, 'id');
            $userIds = array_filter(array_column($orderList, 'user_id'));
            $addressIds = array_filter(array_column($orderList, 'address_id'));
            
            // 第二步：批量获取用户信息
            $users = [];
            if (!empty($userIds)) {
                $userList = Db::name('user')
                    ->field('id, username, nickname, mobile')
                    ->where('id', 'in', $userIds)
                    ->select();
                foreach ($userList as $user) {
                    $users[$user['id']] = $user;
                }
            }
            
            // 第三步：批量获取收货地址信息
            $addresses = [];
            if (!empty($addressIds)) {
                $addressList = Db::name('user_address')
                    ->field('id, name, mobile, province, city, district, address')
                    ->where('id', 'in', $addressIds)
                    ->select();
                foreach ($addressList as $address) {
                    $addresses[$address['id']] = $address;
                }
            }
            
            // 第四步：批量获取订单商品信息
            $orderItems = [];
            $productIds = [];
            if (!empty($orderIds)) {
                $orderItemList = Db::name('order_item')
                    ->field('order_id, product_id, sku_id, sku_name, quantity, price, total_amount')
                    ->where('order_id', 'in', $orderIds)
                    ->select();
                
                foreach ($orderItemList as $item) {
                    $orderItems[$item['order_id']][] = $item;
                    if ($item['product_id']) {
                        $productIds[] = $item['product_id'];
                    }
                }
            }
            
            // 第五步：批量获取商品信息
            $products = [];
            $productImages = [];
            $merchants = [];
            if (!empty($productIds)) {
                $productIds = array_unique($productIds);
                $productList = Db::name('product')
                    ->field('id, name, merchant_id')
                    ->where('id', 'in', $productIds)
                    ->select();
                
                foreach ($productList as $product) {
                    $products[$product['id']] = $product;
                }
                
                // 批量获取商品图片
                $imageList = Db::name('product_image')
                    ->field('product_id, image_url')
                    ->where('product_id', 'in', $productIds)
                    ->select();
                foreach ($imageList as $image) {
                    $productImages[$image['product_id']] = $image['image_url'];
                }
                
                // 批量获取商家信息
                $merchantIds = array_unique(array_filter(array_column($productList, 'merchant_id')));
                if (!empty($merchantIds)) {
                    $merchantList = Db::name('merchant_audit')
                        ->field('merchant_id, store_name')
                        ->where('merchant_id', 'in', $merchantIds)
                        ->select();
                    foreach ($merchantList as $merchant) {
                        $merchants[$merchant['merchant_id']] = $merchant['store_name'];
                    }
                }
            }
            
            $list = $orderList;

            $rows = [];
            foreach ($list as $row) {
                // 从批量获取的数据中获取用户信息
                $user = isset($users[$row['user_id']]) ? $users[$row['user_id']] : null;
                $address = isset($addresses[$row['address_id']]) ? $addresses[$row['address_id']] : null;
                $currentOrderItems = isset($orderItems[$row['id']]) ? $orderItems[$row['id']] : [];
                
                // 处理商品信息
                $productInfo = [];
                $totalQuantity = 0;
                $totalAmount = 0;
                $merchantName = '未知商家';
                
                if (!empty($currentOrderItems)) {
                    foreach ($currentOrderItems as $item) {
                        $product = isset($products[$item['product_id']]) ? $products[$item['product_id']] : null;
                        $imageUrl = isset($productImages[$item['product_id']]) ? $productImages[$item['product_id']] : '';
                        // 直接使用order_item表中的sku_name字段
                        $skuName = $item['sku_name'] ?: '默认规格';
                        
                        // 获取商家名称（从第一个商品获取）
                        if ($merchantName === '未知商家' && $product && isset($product['merchant_id'])) {
                            $merchantName = isset($merchants[$product['merchant_id']]) ? $merchants[$product['merchant_id']] : '未知商家';
                        }
                        
                        // 构建商品详细信息数组
                        $quantity = $item['quantity'] ?: 1;
                        $price = $item['price'] ?: 0;
                        
                        $productDetail = [
                            'id' => $item['product_id'],
                            'name' => ($product && isset($product['name'])) ? $product['name'] : '未知商品',
                            'image' => $imageUrl,
                            'sku_id' => $item['sku_id'],
                            'sku_name' => $skuName,
                            'quantity' => $quantity,
                            'price' => $price,
                            'total_price' => $price * $quantity
                        ];
                        
                        $productInfo[] = $productDetail;
                        $totalQuantity += $quantity;
                        $totalAmount += $price * $quantity;
                    }
                    
                    $avgPrice = $totalQuantity > 0 ? round($totalAmount / $totalQuantity, 2) : 0;
                    $merchantIncome = $totalAmount * 0.9; // 假设商家收益为90%
                } else {
                    // 如果没有订单商品，使用默认值
                    $productInfo = [];
                    $totalQuantity = 1;
                    $avgPrice = $row['total_amount'] ?: 0;
                    $merchantIncome = ($row['total_amount'] ?: 0) * 0.9;
                }
                
                // 直接使用订单表中的attribute_type字段，如果没有则设置默认值
                if (!isset($row['attribute_type']) || $row['attribute_type'] === null) {
                    $row['attribute_type'] = 1; // 默认为权益商品
                }
                
                // 处理收货人信息
                $buyerInfo = '';
                if ($address) {
                    $receiverName = $address['name'] ?: '';
                    $receiverMobile = $address['mobile'] ?: '';
                    
                    if ($receiverName || $receiverMobile) {
                        $buyerInfo = $receiverName;
                        if ($receiverMobile) {
                            $buyerInfo .= ($receiverName ? ' ' : '') . $receiverMobile;
                        }
                    }
                    
                    // 设置地址字段
                    $row['province'] = $address['province'] ?: '';
                    $row['city'] = $address['city'] ?: '';
                    $row['district'] = $address['district'] ?: '';
                    $row['address'] = $address['address'] ?: '';
                }
                
                // 如果地址表没有信息，则从用户表获取买家信息作为备用
                if (!$buyerInfo && $user) {
                    $buyerInfo = ($user['nickname'] ?: '') ?: ($user['username'] ?: '');
                    if ($user['mobile']) {
                        $buyerInfo .= ($buyerInfo ? ' ' : '') . $user['mobile'];
                    }
                }
                
                // 组装返回数据
                $row['merchant_name'] = $merchantName;
                $row['product_info'] = $productInfo;
                $row['total_quantity'] = $totalQuantity;
                $row['avg_price'] = $avgPrice;
                $row['merchant_income'] = round($merchantIncome, 2);
                $row['buyer_info'] = $buyerInfo ?: '暂无信息';
                
                // 添加订单状态和支付类型文本
                $orderStatusList = $this->model->getOrderStatusList();
                $payTypeList = $this->model->getPayTypeList();
                $row['order_status_text'] = isset($orderStatusList[$row['order_status']]) ? $orderStatusList[$row['order_status']] : '';
                $row['pay_type_text'] = isset($payTypeList[$row['pay_type']]) ? $payTypeList[$row['pay_type']] : '';
                
                $rows[] = $row;
            }

            $result = array("total" => $total, "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        // 使用Db链式查询获取订单详情
        $row = Db::name('order')->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取用户信息
        if (isset($row['user_id']) && $row['user_id']) {
            $user = Db::name('user')->where('id', $row['user_id'])->find();
            if ($user) {
                $row['user'] = $user;
            }
        }
        
        // 获取收货地址信息
        if (isset($row['address_id']) && $row['address_id']) {
            $userAddress = Db::name('user_address')->where('id', $row['address_id'])->find();
            if ($userAddress) {
                $row['userAddress'] = $userAddress;
            }
        }
        
        // 获取订单商品信息
        $orderItems = Db::name('order_item')->where('order_id', $row['id'])->select();
        if ($orderItems) {
            // 批量获取商品ID和SKU ID
            $productIds = array_unique(array_filter(array_column($orderItems, 'product_id')));
            $skuIds = array_unique(array_filter(array_column($orderItems, 'sku_id')));
            
            // 批量获取商品信息
            $products = [];
            $merchantIds = [];
            if (!empty($productIds)) {
                $productList = Db::name('product')->where('id', 'in', $productIds)->select();
                foreach ($productList as $product) {
                    $products[$product['id']] = $product;
                    if ($product['merchant_id']) {
                        $merchantIds[] = $product['merchant_id'];
                    }
                }
            }
            
            // 批量获取商家信息
            $merchants = [];
            if (!empty($merchantIds)) {
                $merchantIds = array_unique($merchantIds);
                $merchantList = Db::name('merchant_audit')
                    ->where('merchant_id', 'in', $merchantIds)
                    ->field('merchant_id, store_name')
                    ->select();
                foreach ($merchantList as $merchant) {
                    $merchants[$merchant['merchant_id']] = $merchant['store_name'];
                }
            }
            
            // 批量获取商品图片
            $productImages = [];
            if (!empty($productIds)) {
                $imageList = Db::name('product_image')->where('product_id', 'in', $productIds)->select();
                foreach ($imageList as $image) {
                    $productImages[$image['product_id']] = $image['image_url'];
                }
            }
            
            // 批量获取SKU信息
            $skus = [];
            if (!empty($skuIds)) {
                $skuList = Db::name('product_sku')->where('id', 'in', $skuIds)->select();
                foreach ($skuList as $sku) {
                    $skus[$sku['id']] = $sku;
                }
            }
            
            // 组装数据
            foreach ($orderItems as &$item) {
                // 获取商品信息
                if (isset($item['product_id']) && isset($products[$item['product_id']])) {
                    $product = $products[$item['product_id']];
                    // 添加商品图片
                    if (isset($productImages[$item['product_id']])) {
                        $product['image_url'] = $productImages[$item['product_id']];
                    }
                    // 添加商家信息
                    if (isset($product['merchant_id']) && isset($merchants[$product['merchant_id']])) {
                        $product['merchant_name'] = $merchants[$product['merchant_id']];
                    } else {
                        $product['merchant_name'] = '未知商家';
                    }
                    $item['product'] = $product;
                }
                
                // 获取SKU信息
                if (isset($item['sku_id']) && isset($skus[$item['sku_id']])) {
                    $item['product_sku'] = $skus[$item['sku_id']];
                }
            }
            $row['orderItems'] = $orderItems;
        }
        
        // 获取订单类型
        $row['order_type'] = $this->getOrderType($row['id']);
        
        // 添加订单状态和支付类型文本
        $orderStatusList = $this->model->getOrderStatusList();
        $payTypeList = $this->model->getPayTypeList();
        $row['order_status_text'] = isset($orderStatusList[$row['order_status']]) ? $orderStatusList[$row['order_status']] : '';
        $row['pay_type_text'] = isset($payTypeList[$row['pay_type']]) ? $payTypeList[$row['pay_type']] : '';
        
        // 添加订单类型文本
        $attributeTypeList = [
            1 => '权益商品订单',
            2 => '积分商品订单', 
            3 => '助农商品订单'
        ];
        $row['attribute_type_text'] = isset($attributeTypeList[$row['attribute_type']]) ? $attributeTypeList[$row['attribute_type']] : '权益商品订单';
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 发货
     */
    public function ship($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 检查订单状态
                if ($row['order_status'] != 1) {
                    $this->error('只有已付款的订单才能发货');
                }
                
                $result = false;
                Db::startTrans();
                try {
                    // 更新订单状态为已发货
                    $result = $row->allowField(true)->save([
                        'order_status' => 2,
                        'delivery_time' => time(),
                        'express_company' => $params['express_company'] ?? '',
                        'express_no' => $params['express_no'] ?? ''
                    ]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 打印订单
     */
    public function print($ids = null)
    {
        // 使用Db链式查询获取订单信息
        $row = Db::name('order')->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取用户信息
        if (isset($row['user_id']) && $row['user_id']) {
            $user = Db::name('user')->where('id', $row['user_id'])->find();
            if ($user) {
                $row['user'] = $user;
            }
        }
        
        // 获取收货地址信息
        if (isset($row['address_id']) && $row['address_id']) {
            $userAddress = Db::name('user_address')->where('id', $row['address_id'])->find();
            if ($userAddress) {
                $row['userAddress'] = $userAddress;
            }
        }
        
        // 获取订单商品信息
        $orderItems = Db::name('order_item')->where('order_id', $row['id'])->select();
        if ($orderItems) {
            // 批量获取商品ID和SKU ID
            $productIds = array_unique(array_filter(array_column($orderItems, 'product_id')));
            $skuIds = array_unique(array_filter(array_column($orderItems, 'sku_id')));
            
            // 批量获取商品信息
            $products = [];
            if (!empty($productIds)) {
                $productList = Db::name('product')->where('id', 'in', $productIds)->select();
                foreach ($productList as $product) {
                    $products[$product['id']] = $product;
                }
            }
            
            // 批量获取商品图片
            $productImages = [];
            if (!empty($productIds)) {
                $imageList = Db::name('product_image')->where('product_id', 'in', $productIds)->select();
                foreach ($imageList as $image) {
                    $productImages[$image['product_id']] = $image['image_url'];
                }
            }
            
            // 批量获取SKU信息
            $skus = [];
            if (!empty($skuIds)) {
                $skuList = Db::name('product_sku')->where('id', 'in', $skuIds)->select();
                foreach ($skuList as $sku) {
                    $skus[$sku['id']] = $sku;
                }
            }
            
            // 组装数据
            foreach ($orderItems as &$item) {
                // 获取商品信息
                if (isset($item['product_id']) && isset($products[$item['product_id']])) {
                    $product = $products[$item['product_id']];
                    // 添加商品图片
                    if (isset($productImages[$item['product_id']])) {
                        $product['image_url'] = $productImages[$item['product_id']];
                    }
                    $item['product'] = $product;
                }
                
                // 获取SKU信息
                if (isset($item['sku_id']) && isset($skus[$item['sku_id']])) {
                    $item['product_sku'] = $skus[$item['sku_id']];
                }
            }
            $row['orderItems'] = $orderItems;
        }
        
        // 获取订单类型
        $row['order_type'] = $this->getOrderType($row['id']);
        
        // 添加订单状态和支付类型文本
        $orderStatusList = $this->model->getOrderStatusList();
        $payTypeList = $this->model->getPayTypeList();
        $row['order_status_text'] = isset($orderStatusList[$row['order_status']]) ? $orderStatusList[$row['order_status']] : '';
        $row['pay_type_text'] = isset($payTypeList[$row['pay_type']]) ? $payTypeList[$row['pay_type']] : '';
        
        // 添加订单类型文本
        $attributeTypeList = [
            1 => '权益商品订单',
            2 => '积分商品订单', 
            3 => '助农商品订单'
        ];
        $row['attribute_type_text'] = isset($attributeTypeList[$row['attribute_type']]) ? $attributeTypeList[$row['attribute_type']] : '权益商品订单';
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量发货
     */
    public function batchship()
    {
        if ($this->request->isPost()) {
            $ids = $this->request->post("ids");
            $express_company = $this->request->post("express_company");
            $express_no = $this->request->post("express_no");
            
            if (empty($ids)) {
                $this->error('请选择要发货的订单');
            }
            
            $count = 0;
            Db::startTrans();
            try {
                $list = $this->model->where('id', 'in', $ids)->where('order_status', 1)->select();
                foreach ($list as $row) {
                    $row->save([
                        'order_status' => 2,
                        'delivery_time' => time(),
                        'express_company' => $express_company,
                        'express_no' => $express_no
                    ]);
                    $count++;
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            
            $this->success("成功发货 {$count} 个订单");
        }
        
        return $this->view->fetch();
    }

    /**
     * 批量打印
     */
    public function batchprint()
    {
        $ids = $this->request->param("ids");
        if (empty($ids)) {
            $this->error('请选择要打印的订单');
        }
        
        // 使用Db链式查询获取订单列表
        $list = Db::name('order')->where('id', 'in', $ids)->select();
        
        // 批量获取所有需要的数据
        $orderIds = array_column($list, 'id');
        $userIds = array_unique(array_filter(array_column($list, 'user_id')));
        $addressIds = array_unique(array_filter(array_column($list, 'address_id')));
        
        // 批量获取用户信息
        $users = [];
        if (!empty($userIds)) {
            $userList = Db::name('user')->where('id', 'in', $userIds)->select();
            foreach ($userList as $user) {
                $users[$user['id']] = $user;
            }
        }
        
        // 批量获取地址信息
        $addresses = [];
        if (!empty($addressIds)) {
            $addressList = Db::name('user_address')->where('id', 'in', $addressIds)->select();
            foreach ($addressList as $address) {
                $addresses[$address['id']] = $address;
            }
        }
        
        // 批量获取订单商品信息
        $orderItems = [];
        if (!empty($orderIds)) {
            $itemList = Db::name('order_item')->where('order_id', 'in', $orderIds)->select();
            foreach ($itemList as $item) {
                $orderItems[$item['order_id']][] = $item;
            }
        }
        
        // 获取所有商品ID和SKU ID
        $allProductIds = [];
        $allSkuIds = [];
        foreach ($orderItems as $items) {
            foreach ($items as $item) {
                if ($item['product_id']) {
                    $allProductIds[] = $item['product_id'];
                }
                if ($item['sku_id']) {
                    $allSkuIds[] = $item['sku_id'];
                }
            }
        }
        $allProductIds = array_unique($allProductIds);
        $allSkuIds = array_unique($allSkuIds);
        
        // 批量获取商品信息
        $products = [];
        if (!empty($allProductIds)) {
            $productList = Db::name('product')->where('id', 'in', $allProductIds)->select();
            foreach ($productList as $product) {
                $products[$product['id']] = $product;
            }
        }
        
        // 批量获取商品图片
        $productImages = [];
        if (!empty($allProductIds)) {
            $imageList = Db::name('product_image')->where('product_id', 'in', $allProductIds)->select();
            foreach ($imageList as $image) {
                $productImages[$image['product_id']] = $image['image_url'];
            }
        }
        
        // 批量获取SKU信息
        $skus = [];
        if (!empty($allSkuIds)) {
            $skuList = Db::name('product_sku')->where('id', 'in', $allSkuIds)->select();
            foreach ($skuList as $sku) {
                $skus[$sku['id']] = $sku;
            }
        }
        
        // 为每个订单组装数据
        foreach ($list as &$row) {
            // 获取用户信息
            if (isset($row['user_id']) && isset($users[$row['user_id']])) {
                $row['user'] = $users[$row['user_id']];
            }
            
            // 获取收货地址信息
            if (isset($row['address_id']) && isset($addresses[$row['address_id']])) {
                $row['userAddress'] = $addresses[$row['address_id']];
            }
            
            // 获取订单商品信息
            if (isset($orderItems[$row['id']])) {
                $currentOrderItems = $orderItems[$row['id']];
                foreach ($currentOrderItems as &$item) {
                    // 获取商品信息
                    if (isset($item['product_id']) && isset($products[$item['product_id']])) {
                        $product = $products[$item['product_id']];
                        // 添加商品图片
                        if (isset($productImages[$item['product_id']])) {
                            $product['image_url'] = $productImages[$item['product_id']];
                        }
                        $item['product'] = $product;
                    }
                    
                    // 获取SKU信息
                    if (isset($item['sku_id']) && isset($skus[$item['sku_id']])) {
                        $item['product_sku'] = $skus[$item['sku_id']];
                    }
                }
                $row['orderItems'] = $currentOrderItems;
            }
            
            // 获取订单类型
            $row['order_type'] = $this->getOrderType($row['id']);
            
            // 添加订单状态和支付类型文本
            $orderStatusList = $this->model->getOrderStatusList();
            $payTypeList = $this->model->getPayTypeList();
            $row['order_status_text'] = isset($orderStatusList[$row['order_status']]) ? $orderStatusList[$row['order_status']] : '';
            $row['pay_type_text'] = isset($payTypeList[$row['pay_type']]) ? $payTypeList[$row['pay_type']] : '';
            
            // 添加订单类型文本
            $attributeTypeList = [
                1 => '权益商品订单',
                2 => '积分商品订单', 
                3 => '助农商品订单'
            ];
            $row['attribute_type_text'] = isset($attributeTypeList[$row['attribute_type']]) ? $attributeTypeList[$row['attribute_type']] : '权益商品订单';
        }
        
        $this->view->assign("list", $list);
        return $this->view->fetch();
    }

    /**
     * 导出订单
     */
    public function export()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        
        // 使用Db链式查询获取订单列表
        $list = Db::name('order')
            ->where($where)
            ->order($sort, $order)
            ->select();
        
        // 为每个订单获取用户信息和订单类型
        foreach ($list as &$row) {
            if (isset($row['user_id']) && $row['user_id']) {
                $user = Db::name('user')->where('id', $row['user_id'])->find();
                if ($user) {
                    $row['user'] = $user;
                }
            }
            // 获取订单类型
            $row['order_type'] = $this->getOrderType($row['id']);
        }

        $header = [
            '订单号',
            '用户名',
            '订单类型',
            '订单金额',
            '实付金额',
            '运费',
            '优惠金额',
            '支付方式',
            '订单状态',
            '创建时间',
            '发货时间',
            '收货时间'
        ];

        $data = [];
        foreach ($list as $row) {
            $data[] = [
                isset($row['order_no']) ? $row['order_no'] : '',
                (isset($row['user']) && isset($row['user']['username'])) ? $row['user']['username'] : '',
                isset($row['order_type']) ? $row['order_type'] : '普通订单',
                isset($row['total_amount']) ? $row['total_amount'] : 0,
                isset($row['pay_amount']) ? $row['pay_amount'] : 0,
                isset($row['freight_amount']) ? $row['freight_amount'] : 0,
                isset($row['discount_amount']) ? $row['discount_amount'] : 0,
                (isset($row['pay_type']) && isset($this->model->getPayTypeList()[$row['pay_type']])) ? $this->model->getPayTypeList()[$row['pay_type']] : '',
                (isset($row['order_status']) && isset($this->model->getOrderStatusList()[$row['order_status']])) ? $this->model->getOrderStatusList()[$row['order_status']] : '',
                isset($row['createtime']) ? date('Y-m-d H:i:s', $row['createtime']) : '',
                (isset($row['delivery_time']) && $row['delivery_time']) ? date('Y-m-d H:i:s', $row['delivery_time']) : '',
                (isset($row['receive_time']) && $row['receive_time']) ? date('Y-m-d H:i:s', $row['receive_time']) : ''
            ];
        }

        $filename = '订单列表_' . date('YmdHis') . '.csv';
        
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        fputcsv($output, $header);
        foreach ($data as $row) {
            fputcsv($output, $row);
        }
        fclose($output);
        exit;
    }

    /**
     * 获取订单类型
     * @param int $orderId 订单ID
     * @return string 订单类型文本
     */
    private function getOrderType($orderId)
    {
        // 默认订单类型
        $orderType = '普通订单';
        
        // 获取订单商品信息
        $orderItem = Db::name('order_item')->where('order_id', $orderId)->find();
        if ($orderItem && $orderItem['sku_id']) {
            $attributePrice = Db::name('product_attribute_price')->where('id', $orderItem['sku_id'])->find();
            if ($attributePrice && isset($attributePrice['attribute_type']) && $attributePrice['attribute_type']) {
                // 根据attribute_type值转换为对应的文本
                $attributeTypeMap = [
                    1 => '权益商品',
                    2 => '积分商品', 
                    3 => '助农商品'
                ];
                $orderType = isset($attributeTypeMap[$attributePrice['attribute_type']]) 
                    ? $attributeTypeMap[$attributePrice['attribute_type']] 
                    : '普通订单';
            }
        }
        
        return $orderType;
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    // 只允许删除已取消或已退款的订单
                    if (!in_array($v['order_status'], [4, 5])) {
                        continue;
                    }
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}